package Data;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class MemberDataOperator implements IDataReader,IDataUpdate,IDataWriter{
	
	ArrayList<MemberData>  MemberList;
	String filename = "D:\\MemberData.txt";
	
	public MemberDataOperator(){
		MemberList = new ArrayList<MemberData>();
		File file = new File(filename);
		try{
			MemberData ud = new MemberData();
			BufferedReader bf = new BufferedReader(new FileReader(file));
			String[] record = null;
			String data = "";
			while((data = bf.readLine()) != null){
				if(data.trim().equals("")){
					continue;
				}
				record = splitText(data);
				ud = new MemberData(Integer.parseInt(record[0]),record[1],record[2],record[3],record[4],Double.parseDouble(record[5]),Double.parseDouble(record[6]));
				MemberList.add(ud);
			}
			}catch(IOException ex){
				ex.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public MemberData readDataByID(int id){
		
		for(MemberData ud:MemberList){
			if(ud.getMemberID() == id){
				return ud;
			}
		}
		return null;
	}
	
	public void startUpdate(){
		
	}
	 public ArrayList<MemberData> getMemberData(){
		 return MemberList;
	 }
	
	public String[] splitText(String s){
		String[] data = s.split(",");
		return data;
	}
	
	
	
	
	
	public void readFile(String fileName){
		try{
			String info = "";
			File file = new File(fileName);
			BufferedReader bf= new BufferedReader(new FileReader(file));
			while((info = bf.readLine()) != null){
				System.out.println(info);
			}
		}catch(IOException e){
			e.printStackTrace();
		}
	}

	public void saveData() {

		
	}
	
	
	public boolean saveData(int ID,String name,String birthday,String sex,String contactway,double integralsum,double integralbalance){
		String s = null;
		String s1 = "\r\n";
		try{
			BufferedWriter writer = new BufferedWriter(new FileWriter(new File("D:\\MemberData.txt"),true));
			
				s = ID + "," + name + "," + birthday + "," + sex + "," + contactway + "," + integralsum + "," + integralbalance;
				writer.write(s);
				writer.write(s1);
				writer.close();
				return true;
		}catch(IOException ex){
			ex.printStackTrace();
			return false;
		}
	}
	
	   public static int calculateMintegralSum(String MemberID){
		   int re=0;
		   try{
				File f1=new File("D:\\MemberData.txt");
				FileReader fileReader=new FileReader(f1);
				BufferedReader reader=new BufferedReader(fileReader);
				String line=null;
				while((line=reader.readLine())!=null){
					String[] result=line.split(",");
					if(result[0].equals(MemberID)){
						re=re+Integer.parseInt(result[5]);
					}
			}
			reader.close();
			
		}catch(Exception ex){
			ex.printStackTrace();
			}
		return re;
	   }
	   

	   
	

}
